import {
  CanActivate,
  ExecutionContext,
  Inject,
  Injectable,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { PERMISSION_KEY } from 'src/decorator/permission.decorator';
import { Request } from 'express';
import { PUBLIC_KEY } from 'src/decorator/public.decorator';
import { UserService } from 'src/user/user.service';
@Injectable()
export class PermissionGuard implements CanActivate {
  @Inject(UserService)
  private userService: UserService;

  constructor(private reflector: Reflector) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) {
      return true;
    }

    const request: Request = context.switchToHttp().getRequest();
    const user = request.user;
    console.log('user', user);
    if (!user) {
      return false;
    }

    const requiredPermissions = this.reflector.get<string[]>(
      PERMISSION_KEY,
      context.getHandler(),
    );
    if (!requiredPermissions || requiredPermissions.length === 0) {
      // No permissions required, allow access
      return true;
    }
    const roles = await this.userService.findPermissonByRoleId(
      user.roles.map((role) => role.id),
    );
    const permissions = roles.reduce<string[]>((acc, role) => {
      acc.push(...role.permissions.map((perm) => perm.permission));
      return acc;
    }, []);
    console.log('requiredPermissions', requiredPermissions);

    console.log('permissions', permissions);

    return requiredPermissions.every((perm) => permissions.includes(perm));
  }
}
